<?php

// v 0.1

Simple_Engine::Uses("Simple_Tables");

class Simple_News extends Simple implements IRenderable
{
	private $_newsTable;

	function __construct($newsBlockID)
	{
		$this->_newsTable = new Simple_Tables("Data/".__CLASS__."/".$newsBlockID.".stb");
	}

	function Show()
	{
		Simple_Layout::PreRender("Simple_News", "OutputHolder", array("%news%" => '<? Simple_Layout::PreRender(\"Simple_News", "OutputHolder", array("%news%" => ""'));
	}
	
	function oldShow()
	{
		echo '<table id="news">
				<tr>
					<td class="newsNumber"></td>
					<td>
						<div id="newsTitle" class="bodyTextTitle">Новости</div>
					</td>
				</tr>';
		$count = $this->_newsTable->Count();
		if($count[0] == "error") $count = -1;
		if($count > 0)
		{
			for($i = 1; $i <= $count; $i++)
			{
				echo "<tr>" ;
				echo '<td class="newsNumber">'.$i.'</td>';
				echo '<td class="newsItem">';
				$line = $this->_newsTable->Get($count - $i, array("News"));				
				echo $line["News"];
				echo '<br /><br /></td>';
				echo "</tr>";
			}
		}
		echo('</table>');
		return $сount;
		
		// Simple_Engine::LoadUI(__CLASS__);
	}

	function ShowEditable()
	{
		// js-скрипты управления визуализацией и начало таблицы новостей
		echo "<script>
		function editMode(newsNumber)
		{
			document.getElementById('news' + newsNumber + 'edit').style.display = '';
			document.getElementById('news' + newsNumber).style.display = 'none';
		}
		function showAddNewsForm()
		{
			document.getElementById('addNewsButton').style.display = 'none';
			document.getElementById('addNewsForm').style.display = '';
		}
		function postDeleting(id)
		{
			var f = document.createElement('form');
			f.style.display = 'none';
			f.method = 'post';
			f.action = self.location;
			
			var action = document.createElement('input');
			action.name = 'action';
			action.type = 'hidden';
			action.value = 'deleteNews';
			f.appendChild(action);
			
			var newsNumber = document.createElement('input');
			newsNumber.name = 'newsNumber'
			newsNumber.type = 'hidden';
			newsNumber.value = id;
			f.appendChild(newsNumber);
					
			document.body.appendChild(f);		
			f.submit();
		}
		</script>";
		// Начало таблицы новостей	
		echo "<table id=\"news\">
		<tr>
		<td class=\"newsNumber\"></td>
		<td>
		<div id=\"newsTitle\" class=\"bodyTextTitle\">Новости
			&nbsp;&nbsp;&nbsp;<span id=\"addNewsButton\" onClick=\"showAddNewsForm();\" class=\"submitButton\" style=\"cursor:pointer\">Добавить новость</span>
		</div>
		</td>
		</tr>";
		// Раздел для добавления
		echo "\r\n".'<tr id="addNewsForm" style="display:none">';
		echo "\r\n".'<td class="newsNumber"></td>';
		echo "\r\n".'<td><form method="post">';
		echo "\r\n".'<input type="hidden" name="action" value="addNews" />';
		echo "\r\n".'<textarea name="addNewsValue" style="border:solid 1px black; font-family: Georgia, Times New Roman, Arial, Tahoma; font-size:12px; color: #424242; padding: 3px; width: 100%; height: 80px;">';
		echo "\r\n".'</textarea><input class="submitButton" type="submit" value="Добавить" /></form>';
		echo "\r\n".'<br /><br /></td>';
		echo "\r\n"."</tr>";
		// Обработка добавления
		if(($_POST["action"] == "addNews") && $_POST["addNewsValue"])
		{
			$this->_add($_POST["addNewsValue"]);
		}
		//
		$count = $this->_newsTable->Count();
		if($count[0] == "error") $count = -1;
		if($count > 0)
		{
			// Правка
			if(($_POST["action"] == "editNews") && $_POST["newNewsValue"])
			{
				$this->_edit($count - $_POST["newsNumber"], $_POST["newNewsValue"]);
			}
			for($i = 1; $i <= $count; $i++)
			{
				// Так как $count может менятся внутри цикла, нужна следующая проверка
				if($i > $count) break;
				// Удаление
				if(($_POST["action"] == "deleteNews") && ($_POST["newsNumber"] == $i))
				{
					$this->_delete($count - $_POST["newsNumber"]);
					$count--;
					echo '<tr><td></td><td><div class="newsDeletedNotice">Новость удалена.</div><br /><br /></td></tr>';
					if ($count == 0) break;
					if($i > $count) break;
				}
				// Всю следующую чушь логичнее реализовать шаблонами
				// Раздел вывода
				echo "\r\n".'<tr id="news'.$i.'">';
				echo "\r\n".'<td class="newsNumber">'.$i.'</td>';
				echo "\r\n".'<td class="newsItem">';	
				$line = $this->_newsTable->Get($count - $i, array("News"));
				echo $line["News"];
				echo "\r\n".'<table class="newsControls">';
				echo "\r\n".'<tr><td class="newsControls">';
				echo "\r\n".'<a href="#" onclick="editMode(\''.$i.'\')">Править</a>'; 				
				echo "\r\n".'</td><td class="newsControls">';			
				echo "\r\n".'<a href="#" onclick="postDeleting('.$i.');">Удалить</a>';																
				echo "\r\n".'</td></tr>';
				echo "\r\n".'</table>';
				echo "\r\n".'<br /><br /></td>';
				echo "\r\n"."</tr>";
				// Вывод редактируемого варианта
				echo "\r\n".'<tr id="news'.$i.'edit" style="display:none">';
				echo "\r\n".'<td class="newsNumber">'.$i.'</td>';
				echo "\r\n".'<td class="newsItem">';
				echo "\r\n".'<form id="editNewsControlForm'.$i.'" method="post">';
				echo "\r\n".'<input type="hidden" name="action" value="editNews" />';
				echo "\r\n".'<input type="hidden" name="newsNumber" value="'.$i.'" />';				
				echo "\r\n".'<textarea name="newNewsValue" style="border:solid 1px black; font-family: Georgia, Times New Roman, Arial, Tahoma; font-size:12px; color: #424242; padding: 3px; width: 100%; height: 80px;">';
				echo str_replace("<br />", "\r\n", $line["News"]);
				echo "\r\n".'</textarea><br /><br /><input class="submitButton" type="submit" value="Сохранить" />';
				echo "\r\n".'</form>';
				echo "\r\n".'<br /><br /></td>';
				echo "\r\n"."</tr>";				
			}
		}
		echo '</table>';
		return $count;		
		// Simple_Engine::LoadUI(__CLASS__);
	}

	private function _add($NewsText)
	{
		$NewsText = htmlspecialchars($NewsText);
		$NewsText = str_replace("\r\n", "<br />", $NewsText);
		$NewsText = str_replace("\n", "<br />", $NewsText);
		
		$this->_newsTable->Add(array("News"), array($NewsText));
		$this->_newsTable->Save();
		$this->_newsTable->Refresh();		
		return true;
	}

	private function _edit($NewsNumber, $NewsText)
	{
		$NewsText = htmlspecialchars($NewsText);
		$NewsText = str_replace("\r\n", "<br />", $NewsText);
		$NewsText = str_replace("\n", "<br />", $NewsText);
		if(substr($NewsText, -4) == "\r\n") $NewsText = substr($NewsText, 0, -4);
		else if(substr($NewsText, -2) == "\n") $NewsText = substr($NewsText, 0, -2);
		
		$this->_newsTable->Update($NewsNumber, array("News"), array($NewsText));
		$this->_newsTable->Save();
		$this->_newsTable->Refresh();		
		return true;
	}

	private function _delete($NewsNumber)
	{
		$this->_newsTable->Delete($NewsNumber);	
		$this->_newsTable->Save();
		$this->_newsTable->Refresh();
	}
}

?>